<template>
  <div class="entry-data">
    <el-card shadow="never">
      <div slot="header" class="card-header">
        <span>关单数据</span>
      </div>

      <!-- 查询表单 -->
      <el-form :inline="true" :model="queryForm" size="small" class="query-form">
        <el-form-item label="报关单号">
          <el-input v-model="queryForm.entryId" placeholder="请输入报关单号" clearable style="width: 180px;"/>
        </el-form-item>
        <!-- <el-form-item label="企业名称">
          <el-input v-model="queryForm.tradeName" placeholder="请输入企业名称" clearable style="width: 180px;"/>
        </el-form-item> -->
        <el-form-item label="选择企业">
          <el-select v-model="queryForm.tradeCoScc" placeholder="请选择企业" clearable filterable style="width: 380px;">
            <el-option
              v-for="item in companyTaxNoList"
              :key="item.taxNo"
              :label="`${item.name} (${item.taxNo})`"
              :value="item.taxNo">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出口日期">
          <el-date-picker
            v-model="queryForm.ieDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyyMMdd"
            clearable
            style="width: 260px;"/>
        </el-form-item>
        <el-form-item label="申报日期">
          <el-date-picker
            v-model="queryForm.dDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyyMMdd"
            clearable
            style="width: 260px;"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
          <el-button type="success" icon="el-icon-download" @click="handleSyncHistory">同步历史关单</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="entryId" label="报关单号" width="180" fixed/>
<!--        <el-table-column prop="tradeName" label="企业名称" width="220"/>-->
<!--        <el-table-column prop="tradeCoScc" label="企业税号" width="180"/>-->
        <el-table-column prop="ieDate" label="出口日期" width="100"/>
        <el-table-column prop="dDate" label="申报日期" width="100"/>
        <el-table-column prop="customMasterName" label="主管海关" width="150"/>
        <el-table-column prop="iePortName" label="进出口岸" width="150"/>
        <el-table-column prop="tradeModeName" label="贸易方式" width="150"/>
        <el-table-column prop="trafModeName" label="运输方式" width="120"/>
        <el-table-column prop="trafName" label="运输工具" width="150"/>
        <el-table-column prop="voyageNo" label="航次号" width="120"/>
        <el-table-column prop="billNo" label="提运单号" width="150"/>
        <el-table-column prop="ownerName" label="货主单位" width="200"/>
        <el-table-column prop="distinatePortName" label="目的港" width="150"/>
        <el-table-column prop="grossWt" label="毛重" width="100"/>
        <el-table-column prop="netWt" label="净重" width="100"/>
        <el-table-column prop="packNo" label="件数" width="80"/>
        <el-table-column prop="wrapTypeName" label="包装种类" width="120"/>
        <el-table-column label="操作" width="100" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleView(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryForm.current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryForm.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 详情对话框（完整海关报关单样式） -->
    <el-dialog
      :visible.sync="detailVisible"
      width="1300px"
      top="3vh"
      :close-on-click-modal="false"
      custom-class="entry-detail-dialog">
      <div class="customs-sheet">
        <!-- 标题和海关编号 -->
        <div class="sheet-header">
          <div class="sheet-title">中华人民共和国海关出口货物报关单</div>
          <div class="customs-no">海关编号：{{ detail.entryId || '-' }}</div>
        </div>

        <!-- 海关报关单主体表格 -->
        <table class="customs-table">
          <!-- 第一行：出口口岸 -->
          <tr>
            <th rowspan="2" class="row-label">出口口岸（{{ detail.iePort }}）<br/>{{detail.iePortName}}</th>
            <th colspan="3" class="col-label">备案号</th>
            <th class="col-label">出口日期</th>
            <th class="col-label">申报日期</th>
          </tr>
          <tr>
            <td colspan="3">{{ detail.preEntryId || '-' }}</td>
            <td>{{ detail.ieDate || '-' }}</td>
            <td>{{ detail.dDate || '-' }}</td>
          </tr>

          <!-- 境内收发货人 -->
          <tr>
            <th rowspan="3" class="row-label">境内收发货人（{{ detail.tradeCo || '-' }}）</th>
            <th colspan="2" class="col-label">运输方式</th>
            <th class="col-label">运输工具名称</th>
            <th colspan="2" class="col-label">提运单号</th>
          </tr>
          <tr>
            <td colspan="2">{{ detail.trafModeName || detail.trafMode || '-' }}</td>
            <td>{{ detail.trafName || '-' }}</td>
            <td colspan="2">{{ detail.billNo || '-' }}</td>
          </tr>
          <tr>
            <td colspan="5">{{ detail.tradeName || '-' }}</td>
          </tr>

          <!-- 生产销售单位 -->
          <tr>
            <th rowspan="3" class="row-label">生产销售单位（{{ detail.tradeCo || '-' }}）</th>
            <th colspan="2" class="col-label">贸易方式（{{ detail.tradeMode || '-' }}）</th>
            <th class="col-label">征免性质</th>
            <th colspan="2" class="col-label">结汇方式</th>
          </tr>
          <tr>
            <td colspan="2">{{ detail.tradeModeName || '-' }}</td>
            <td>{{ detail.cutMode || '-' }}</td>
            <td colspan="2">-</td>
          </tr>
          <tr>
            <td colspan="5">{{ detail.ownerName || detail.tradeName || '-' }}</td>
          </tr>

          <!-- 许可证号 -->
          <tr>
            <th rowspan="2" class="row-label">许可证号</th>
            <th colspan="1" class="col-label">运抵国（地区）</th>
            <th colspan="4" class="col-label">提运港（地区）（{{ detail.distinatePort || '-' }}）<br/>-</th>
          </tr>
          <tr>
            <td colspan="1">{{ detail.destinationCountry || '-' }}</td>
            <th class="col-label">境内货源地</th>
            <td colspan="3">-</td>
          </tr>

          <!-- 批准文号 -->
          <tr>
            <th rowspan="2" class="row-label">批准文号</th>
            <th class="col-label">成交方式</th>
            <th class="col-label">运费</th>
            <th class="col-label">保费</th>
            <th colspan="2" class="col-label">杂费</th>
          </tr>
          <tr>
            <td>-</td>
            <td>-</td>
            <td>-</td>
            <td colspan="2">-</td>
          </tr>

          <!-- 合同协议号 -->
          <tr>
            <th rowspan="2" class="row-label">合同协议号</th>
            <th class="col-label">件数</th>
            <th class="col-label">包装种类</th>
            <th class="col-label">毛重（千克）</th>
            <th colspan="2" class="col-label">净重（千克）</th>
          </tr>
          <tr>
            <td>{{ detail.packNo || '-' }}</td>
            <td>{{ detail.wrapTypeName || detail.wrapType || '-' }}</td>
            <td>{{ detail.grossWt || '-' }}</td>
            <td colspan="2">{{ detail.netWt || '-' }}</td>
          </tr>

          <!-- 集装箱号 -->
          <tr>
            <th class="row-label">集装箱号</th>
            <td colspan="3">-</td>
            <th class="col-label">随附单证</th>
            <td colspan="1">{{ detail.certMark || '-' }}</td>
          </tr>

          <!-- 标记唛码及备注 -->
          <tr>
            <th class="row-label">标记唛码及备注</th>
            <td colspan="5">{{ detail.noteS || '-' }}</td>
          </tr>
        </table>

        <!-- 商品明细 -->
        <div class="sheet-subtitle">商品明细</div>
        <div class="goods-table-wrapper">
          <table class="goods-table">
            <thead>
              <tr>
                <th class="goods-th" style="width: 60px;">序号</th>
                <th class="goods-th" style="width: 110px;">商品编码</th>
                <th class="goods-th" style="width: 220px;">商品名称、规格型号</th>
                <th class="goods-th" style="width: 110px;">数量/单位</th>
                <th class="goods-th" style="width: 110px;">数量及单位</th>
                <th class="goods-th" style="width: 100px;">目的国(地区)</th>
                <th class="goods-th" style="width: 90px;">单价</th>
                <th class="goods-th" style="width: 100px;">总价</th>
                <th class="goods-th" style="width: 70px;">币制</th>
                <th class="goods-th" style="width: 90px;">征免</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in detailItems" :key="index">
                <td class="goods-td center">{{ item.gNo || (index + 1) }}</td>
                <td class="goods-td">{{ item.codeT || '-' }}</td>
                <td class="goods-td">
                  <div>{{ item.gName || '-' }}</div>
                  <div class="spec-text">{{ item.gModel || '' }}</div>
                </td>
                <td class="goods-td">{{ (item.qty1 || '-') + ' ' + (item.qty1Unit || '') }}</td>
                <td class="goods-td">{{ (item.qty2 || item.qty || '-') + ' ' + (item.qty2Unit || item.qtyUnit || '') }}</td>
                <td class="goods-td">{{ item.destinationCountry || '-' }}</td>
                <td class="goods-td right">{{ item.declPrice || '-' }}</td>
                <td class="goods-td right">{{ item.declTotal || '-' }}</td>
                <td class="goods-td center">{{ item.tradeCurr || '-' }}</td>
                <td class="goods-td center">{{ item.dutyMode || '-' }}</td>
              </tr>
              <tr v-if="!detailItems || detailItems.length === 0">
                <td colspan="10" class="goods-td center" style="color: #909399;">暂无商品明细</td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 税费征收情况 -->
        <div class="sheet-subtitle">税费征收情况</div>
        <table class="tax-table">
          <tr>
            <th rowspan="4" style="width: 10%;">录入员</th>
            <th rowspan="4" style="width: 12%;">录入单位</th>
            <th rowspan="4" style="width: 35%;">兹声明以上申报无讹并承担法律责任</th>
            <th colspan="2" style="width: 43%;">海关审单批注及放行日期（签章）</th>
          </tr>
          <tr>
            <th style="width: 21.5%;">审单</th>
            <th style="width: 21.5%;">审价</th>
          </tr>
          <tr>
            <td>-</td>
            <td>-</td>
          </tr>
          <tr>
            <th>征收</th>
            <th>统计</th>
          </tr>
          <tr>
            <th>报关员</th>
            <td rowspan="3" colspan="2" style="text-align: center; vertical-align: middle;">申报单位（签章）</td>
            <td>-</td>
            <td>-</td>
          </tr>
          <tr>
            <th>单位地址</th>
            <th>查验</th>
            <th>放行</th>
          </tr>
          <tr>
            <th>邮编</th>
            <td>-</td>
            <td>-</td>
          </tr>
          <tr>
            <td>-</td>
            <th>电话</th>
            <th>填制日期</th>
            <td>-</td>
            <td>-</td>
          </tr>
        </table>
      </div>
    </el-dialog>

    <!-- 同步历史关单对话框 -->
    <el-dialog
      title="同步历史关单"
      :visible.sync="syncDialogVisible"
      width="600px"
      :close-on-click-modal="false">
      <el-form :model="syncForm" :rules="syncRules" ref="syncForm" label-width="120px">
        <el-form-item label="选择企业" prop="companyTaxNo">
          <el-select v-model="syncForm.companyTaxNo" placeholder="请选择企业" clearable filterable style="width: 100%;">
            <el-option
              v-for="item in companyTaxNoList"
              :key="item.taxNo"
              :label="`${item.name} (${item.taxNo})`"
              :value="item.taxNo">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="同步年份" prop="year">
          <el-date-picker
            v-model="syncForm.year"
            type="year"
            placeholder="选择年份"
            value-format="yyyy"
            style="width: 100%;"/>
        </el-form-item>
      </el-form>

      <!-- 同步进度 -->
      <div v-if="syncing" class="sync-progress">
        <el-progress :percentage="syncProgress" :status="syncStatus"></el-progress>
        <div class="sync-info">
          <p>{{ syncMessage }}</p>
          <div class="month-list">
            <el-tag
              v-for="month in syncMonths"
              :key="month.month"
              :type="month.status === 'success' ? 'success' : month.status === 'error' ? 'danger' : month.status === 'running' ? 'warning' : 'info'"
              style="margin: 5px;">
              {{ month.label }}: {{ month.count || 0 }}条
            </el-tag>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="syncDialogVisible = false" :disabled="syncing">取消</el-button>
        <el-button type="primary" @click="handleStartSync" :loading="syncing">{{ syncing ? '同步中...' : '开始同步' }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getEntryList, getEntryDetail, syncHistoryData } from '@/api/entry'
import { getCompanyTaxNos } from '@/api/task'

export default {
  name: 'EntryData',
  data() {
    return {
      loading: false,
      queryForm: {
        current: 1,
        size: 10,
        entryId: '',
        tradeName: '',
        tradeCoScc: '',
        ieDateRange: null,
        dDateRange: null
      },
      companyTaxNoList: [],
      tableData: [],
      total: 0,
      detailVisible: false,
      detail: {},
      detailItems: [],
      detailLoading: false,
      // 同步历史关单
      syncDialogVisible: false,
      syncForm: {
        companyTaxNo: '',
        year: new Date().getFullYear().toString()
      },
      syncRules: {
        companyTaxNo: [
          { required: true, message: '请输入企业税号', trigger: 'blur' }
        ],
        year: [
          { required: true, message: '请选择年份', trigger: 'change' }
        ]
      },
      syncing: false,
      syncProgress: 0,
      syncStatus: '',
      syncMessage: '',
      syncMonths: []
    }
  },
  mounted() {
    this.loadCompanyTaxNos()
    this.loadData()
  },
  methods: {
    loadCompanyTaxNos() {
      getCompanyTaxNos().then(res => {
        this.companyTaxNoList = res.data || []
      }).catch(err => {
        console.error('加载企业税号列表失败:', err)
      })
    },
    loadData() {
      this.loading = true
      // 构建查询参数
      const params = {
        current: this.queryForm.current,
        size: this.queryForm.size,
        entryId: this.queryForm.entryId,
        //tradeName: this.queryForm.tradeName,
        tradeCoScc: this.queryForm.tradeCoScc
      }
      // 处理出口日期范围
      if (this.queryForm.ieDateRange && this.queryForm.ieDateRange.length === 2) {
        params.ieDateStart = this.queryForm.ieDateRange[0]
        params.ieDateEnd = this.queryForm.ieDateRange[1]
      }
      // 处理申报日期范围
      if (this.queryForm.dDateRange && this.queryForm.dDateRange.length === 2) {
        params.dDateStart = this.queryForm.dDateRange[0]
        params.dDateEnd = this.queryForm.dDateRange[1]
      }

      getEntryList(params).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleQuery() {
      this.queryForm.current = 1
      this.loadData()
    },
    handleReset() {
      this.queryForm = {
        current: 1,
        size: 10,
        entryId: '',
        tradeName: '',
        tradeCoScc: '',
        ieDateRange: null,
        dDateRange: null
      }
      this.loadData()
    },
    handleSizeChange(val) {
      this.queryForm.size = val
      this.loadData()
    },
    handleCurrentChange(val) {
      this.queryForm.current = val
      this.loadData()
    },
    handleView(row) {
      this.detailVisible = true
      this.detailLoading = true

      // 调用后端接口获取该报关单的所有明细
      getEntryDetail(row.entryId).then(res => {
        if (res.data && res.data.length > 0) {
          // 第一条作为抬头信息
          this.detail = { ...res.data[0] }

          // 所有数据作为明细列表（后端返回驼峰命名）
          this.detailItems = res.data.map(x => ({
            gNo: x.gNo,
            codeT: x.codeT,
            gName: x.gName,
            gModel: x.gModel,
            qty1: x.qty1,
            qty1Unit: x.qty1Unit,
            qty2: x.qty2,
            qty2Unit: x.qty2Unit,
            qty: x.qty,
            qtyUnit: x.qtyUnit,
            destinationCountry: x.destinationCountry,
            declPrice: x.declPrice,
            declTotal: x.declTotal,
            tradeCurr: x.tradeCurr,
            dutyMode: x.dutyMode
          }))
        }
        this.detailLoading = false
      }).catch(err => {
        this.$message.error('获取关单详情失败')
        this.detailLoading = false
      })
    },
    // 打开同步历史关单对话框
    handleSyncHistory() {
      this.syncDialogVisible = true
      this.syncing = false
      this.syncProgress = 0
      this.syncStatus = ''
      this.syncMessage = ''
      this.syncMonths = []
    },
    // 开始同步
    handleStartSync() {
      this.$refs.syncForm.validate(async (valid) => {
        if (!valid) return

        this.syncing = true
        this.syncProgress = 0
        this.syncStatus = ''
        this.syncMessage = '准备同步...'

        // 初始化12个月
        this.syncMonths = []
        for (let i = 1; i <= 12; i++) {
          this.syncMonths.push({
            month: i,
            label: `${this.syncForm.year}-${i.toString().padStart(2, '0')}`,
            status: 'pending',
            count: 0
          })
        }

        let totalCount = 0
        let successMonths = 0
        let failedMonths = 0

        // 逐月同步
        for (let i = 0; i < 12; i++) {
          const month = i + 1
          const monthStr = month.toString().padStart(2, '0')

          // 计算当月起止日期
          const startDate = `${this.syncForm.year}${monthStr}01`
          const endDate = this.getMonthEndDate(this.syncForm.year, month)

          this.syncMonths[i].status = 'running'
          this.syncMessage = `正在同步 ${this.syncForm.year}年${monthStr}月...`

          try {
            const res = await syncHistoryData({
              companyTaxNo: this.syncForm.companyTaxNo,
              startDate: startDate,
              endDate: endDate
            })

            // 后端返回格式：{ code: 200, message: "...", data: 53 }
            if (res.code === 200) {
              this.syncMonths[i].status = 'success'
              this.syncMonths[i].count = res.data || 0
              totalCount += (res.data || 0)
              successMonths++
            } else {
              this.syncMonths[i].status = 'error'
              failedMonths++
            }
          } catch (error) {
            this.syncMonths[i].status = 'error'
            failedMonths++
            console.error(`${monthStr}月同步失败:`, error)
          }

          // 更新进度
          this.syncProgress = Math.round(((i + 1) / 12) * 100)
        }

        // 同步完成
        this.syncing = false
        if (failedMonths === 0) {
          this.syncStatus = 'success'
          this.syncMessage = `同步完成！共同步 ${totalCount} 条关单明细数据`
          this.$message.success(this.syncMessage)
        } else {
          this.syncStatus = 'warning'
          this.syncMessage = `同步完成！成功 ${successMonths} 个月，失败 ${failedMonths} 个月，共 ${totalCount} 条明细数据`
          this.$message.warning(this.syncMessage)
        }

        // 刷新列表
        this.loadData()
      })
    },
    // 获取月末日期
    getMonthEndDate(year, month) {
      const lastDay = new Date(year, month, 0).getDate()
      return `${year}${month.toString().padStart(2, '0')}${lastDay}`
    }
  }
}
</script>

<style scoped>
.entry-data {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.query-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
/* 海关报关单详情样式 */
.customs-sheet {
  font-size: 13px;
  color: #333;
}

.sheet-header {
  position: relative;
  margin-bottom: 10px;
}

.sheet-title {
  text-align: center;
  font-size: 20px;
  font-weight: 700;
  margin-bottom: 5px;
}

.customs-no {
  text-align: right;
  font-size: 13px;
  margin-bottom: 8px;
}

/* 主表格 */
.customs-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 15px;
}

.customs-table th,
.customs-table td {
  border: 1px solid #333;
  padding: 4px 6px;
  font-size: 12px;
  line-height: 1.4;
  vertical-align: middle;
}

.customs-table th {
  background: #f5f5f5;
  font-weight: 600;
}

.customs-table .row-label {
  text-align: left;
  padding-left: 8px;
  width: 18%;
  white-space: nowrap;
}

.customs-table .col-label {
  text-align: center;
  background: #f5f5f5;
  font-weight: 600;
}

.customs-table td {
  background: #fff;
  padding: 4px 6px;
  text-align: center;
}

/* 商品明细表格 */
.sheet-subtitle {
  margin: 12px 0 6px;
  font-weight: 600;
  font-size: 14px;
}

/* 商品表格容器 - 超过8行显示滚动条 */
.goods-table-wrapper {
  max-height: 300px; /* 约8行的高度 */
  overflow-y: auto;
  border: 1px solid #333;
  margin-bottom: 15px;
}

/* 美化滚动条 */
.goods-table-wrapper::-webkit-scrollbar {
  width: 8px;
}

.goods-table-wrapper::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.goods-table-wrapper::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 4px;
}

.goods-table-wrapper::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.goods-table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}

/* 固定表头 */
.goods-table thead {
  position: sticky;
  top: 0;
  z-index: 10;
  background: #f5f5f5;
}

.goods-table .goods-th {
  border-right: 1px solid #333;
  border-bottom: 1px solid #333;
  padding: 5px 4px;
  font-size: 12px;
  line-height: 1.4;
  background: #f5f5f5;
  font-weight: 600;
  text-align: center;
  vertical-align: middle;
}

.goods-table .goods-th:first-child {
  border-left: none;
}

.goods-table .goods-td {
  border-right: 1px solid #333;
  border-bottom: 1px solid #333;
  padding: 4px 5px;
  font-size: 11px;
  line-height: 1.4;
  background: #fff;
  vertical-align: middle;
}

.goods-table .goods-td:first-child {
  border-left: none;
}

.goods-table .goods-td.center {
  text-align: center;
}

.goods-table .goods-td.right {
  text-align: right;
}

.spec-text {
  color: #666;
  font-size: 10px;
  margin-top: 2px;
  line-height: 1.3;
}

/* 税费征收情况表格 */
.tax-table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}

.tax-table th,
.tax-table td {
  border: 1px solid #333;
  padding: 4px 6px;
  font-size: 12px;
  line-height: 1.5;
  vertical-align: middle;
}

.tax-table th {
  background: #f5f5f5;
  font-weight: 600;
  text-align: center;
}

.tax-table td {
  background: #fff;
  padding: 4px 6px;
}

/* 同步进度样式 */
.sync-progress {
  margin-top: 20px;
}

.sync-info {
  margin-top: 15px;
}

.sync-info p {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.month-list {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

/* 详情对话框样式 */
.entry-detail-dialog {
  max-height: 90vh;
  overflow-y: auto;
}

.entry-detail-dialog .el-dialog__body {
  padding: 10px 20px;
  max-height: calc(90vh - 60px);
  overflow-y: auto;
}
</style>

